package com.github.jspxnet.worktask.service.impl;

import com.github.jspxnet.sioc.annotation.Bean;
import com.github.jspxnet.sioc.annotation.Ref;
import com.github.jspxnet.utils.BeanUtil;
import com.github.jspxnet.worktask.dao.ConfWorkFlowDAO;
import com.github.jspxnet.worktask.env.JWorkTask;
import com.github.jspxnet.worktask.model.dto.ConfFlowJobDto;
import com.github.jspxnet.worktask.model.dto.ConfFlowNodeDto;
import com.github.jspxnet.worktask.model.dto.ConfWorkFlowDto;
import com.github.jspxnet.worktask.model.enums.FlowNodeEnumType;
import com.github.jspxnet.worktask.service.WorkFlowConfService;
import com.github.jspxnet.worktask.table.ConfFlowJob;
import com.github.jspxnet.worktask.table.ConfFlowNode;
import com.github.jspxnet.worktask.table.ConfWorkFlow;
import com.github.jspxnet.worktask.util.WorkFlowUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Bean(namespace = JWorkTask.namespace)
public class WorkFlowConfServiceImpl implements WorkFlowConfService
{
    @Ref
    private ConfWorkFlowDAO confWorkFlowDAO;

    /**
     * 用来判断是否有权限能够发起流程
     * @param flowNo 流程编号
     * @param namespace 命名空间
     * @return 得到第一个节点
     */
    @Override
    public ConfFlowNode getStartNode(String flowNo, String namespace)
    {
        ConfWorkFlow confWorkFlow = confWorkFlowDAO.getByFlowNo(flowNo,namespace);
        return WorkFlowUtil.getStartConfWorkFlow(confWorkFlow);
    }


    /**
     *
     * @param flowNo 流程编号
     * @param namespace  命名空间
     * @return 流程完整配置
     */
    @Override
    public ConfWorkFlowDto getByFlowNo(String flowNo, String namespace)
    {
        ConfWorkFlow confWorkFlow = confWorkFlowDAO.getByFlowNo(flowNo,namespace);

        ConfWorkFlowDto confWorkFlowDto= BeanUtil.copy(confWorkFlow, ConfWorkFlowDto.class);

        List<ConfFlowJob> jobList = confWorkFlowDAO.getConfFlowJobList(flowNo,namespace);
        Map<String,ConfFlowJobDto> jobMap = new HashMap<>();
        for (ConfFlowJob job:jobList)
        {
            jobMap.put(job.getNodeId(),BeanUtil.copy(job, ConfFlowJobDto.class));
        }
        for (ConfFlowNodeDto dto:confWorkFlowDto.getNodeList())
        {
            if (FlowNodeEnumType.TASK.getValue()==dto.getFlowNodeType())
            {
                dto.setConfFlowJob(jobMap.get(dto.getNodeId()));
            }
        }
        return confWorkFlowDto;
    }
}
